package cn.tsmchina.one.util;

import javax.servlet.http.HttpServletRequest;

import cn.tsmchina.one.domain.user.Customer;
import cn.tsmchina.one.service.user.CustomerService;

public class LoginUtil {
	public static final long getCustomerId(HttpServletRequest request, CustomerService customerService) {
		String loginId = request.getParameter("cid");
		if(loginId!=null) {
			int cid = -1;
			boolean inParam = true;
			try {
				cid = Integer.parseInt(loginId);
			} catch (Exception e) {
				inParam=false;
			}
			if(inParam) {
				Customer customer = customerService.getCustomerByLoginId(cid);
				return customer.getId();
			}
		}
		Customer customer = (Customer) request.getSession().getAttribute("customer");
		if(customer==null) {
			customer = (Customer) request.getSession().getAttribute("historyCustomer");
//			if(!request.getServletPath().equals("/index"))
			if(customer==null) {
				throw new MissCidException();
			} else {
				return customer.getId(); 
			}
		} else {
			return customer.getId();
		}
	}
	
	public static final Integer getCustomerType(HttpServletRequest request) {

		Customer customer = (Customer) request.getSession().getAttribute("customer");
		if(customer==null) {
			customer = (Customer) request.getSession().getAttribute("historyCustomer");
//			if(!request.getServletPath().equals("/index"))
			if(customer==null) {
				throw new MissCidException();
			} else {
				return customer.getType(); 
			}
		} else {
			return customer.getType();
		}
	}
	
	public static final Integer getLoginId(HttpServletRequest request, CustomerService customerService) {

		Customer customer = (Customer) request.getSession().getAttribute("customer");
		if(customer==null) {
			customer = (Customer) request.getSession().getAttribute("historyCustomer");
//			if(!request.getServletPath().equals("/index"))
			if(customer==null) {
				throw new MissCidException();
			} else {
				return customer.getLoginId(); 
			}
		} else {
			return customer.getLoginId();
		}
	}
}
